package net.bblot.lottery.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import com.marsscp.cp.R;
import net.bblot.lottery.api.ApiClinet;
import net.bblot.lottery.api.SimpleResponseListener;
import net.bblot.lottery.api.bean.Data;
import net.bblot.lottery.api.request.GetAds;
import net.bblot.lottery.api.result.ExcuterResult;
import net.bblot.lottery.api.task.HttpTask;

import java.io.File;
import java.util.Random;

public class AdsPopwindowUtil {
	public final static String TAG = "AdsPopwindowUtil";
	public static int seconds = 20;

	public static PopupWindow showAdsPopWindow(final Activity mActivity) {
		seconds = 20;
		final View v = mActivity.getLayoutInflater().inflate(R.layout.pop_ads, null);
		final PopupWindow pw = new PopupWindow(v, FrameLayout.LayoutParams.MATCH_PARENT,
				FrameLayout.LayoutParams.MATCH_PARENT, true);
		ImageView iView = (ImageView) v.findViewById(R.id.pop_ads_iv);
		final TextView tv = (TextView) v.findViewById(R.id.pop_ads_tv_skip);
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mActivity.getApplicationContext())
				.memoryCacheSizePercentage(15).build();
		ImageLoader.getInstance().init(config);
		// Logger.e("AdsPopwindowUtil", "48");
		final GetAds.Result result = getAdsInfo(mActivity.getApplicationContext());
		if (result == null || result.imagearray == null || result.imagearray.size() == 0) {
			return null;
		}
		// Logger.e("AdsPopwindowUtil", "52");
		Random random = new Random();
		final GetAds.Result.Image image = result.imagearray.get(random.nextInt(result.imagearray.size()));
		if (TextUtils.isEmpty(image.getPic_url())) {
			return null;
		}
		File file = ImageLoader.getInstance().getDiskCache().get(image.getPic_url());
		if (!file.exists()) {
			Logger.e("AdsPopwindowUtil", "56");
			return null;
		}
		// Logger.e("AdsPopwindowUtil", Md5Utils.getFileMD5(file));
		iView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					// TODO Auto-generated method stub
					if (!TextUtils.isEmpty(image.getLink_url())) {
						Intent intent = new Intent();
						intent.setAction("android.intent.action.VIEW");
						Uri content_url = Uri.parse(image.getLink_url());
						intent.setData(content_url);
						mActivity.startActivity(intent);
					}
				}catch (Exception e){

				}


			}
		});
		tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (pw != null && pw.isShowing()) {
					pw.dismiss();
				}
			}
		});

		pw.setOutsideTouchable(false);
		if (pw != null && !pw.isShowing()) {
			pw.showAtLocation(v, Gravity.BOTTOM, 0, 0);
		}
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				seconds--;
				if (seconds > 3) {
					tv.setText("跳过  " + 3);
				}else{
					tv.setText("跳过  " + seconds);
				}
				if (seconds <= 0) {
					pw.dismiss();
				} else {
					v.postDelayed(this, 1000);
				}
			}
		};
		v.postDelayed(runnable, 1000);
		tv.setText("跳过  " + seconds);
		try {
			Bitmap bDrawable = ImageLoader.getInstance().loadImageSync(image.getPic_url());
			iView.setImageBitmap(bDrawable);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return pw;
	}

	public static void setStopTime() {
		seconds = 4;

	}

	public static void requestAdsInfo(final Context mActivity) {
		// Logger.e(TAG, "115");
		if (!ImageLoader.getInstance().isInited()) {
			ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(mActivity.getApplicationContext()));
		}
		SimpleResponseListener simpleResponseListener = new SimpleResponseListener() {
			@Override
			public void onGetResult(String responsCode, ExcuterResult er) {
				// TODO Auto-generated method stub
				// Logger.e(TAG, "120");
				try {
					Gson gson = new Gson();
					Data data = gson.fromJson(er.getResult(), Data.class);
					// Logger.e(TAG, "124" + data.getInfo());
					if (data.getInfo() != null) {
						// Logger.e(TAG, "126");
						DisplayImageOptions imageOptions = new DisplayImageOptions.Builder().cacheOnDisk(true).build();
						GetAds.Result gr = gson.fromJson(data.getInfo(), GetAds.Result.class);
						// Logger.e(TAG, "128");
						saveAdsInfo(mActivity.getApplicationContext(), gr);
						if (gr.imagearray != null) {
							for (int i = 0; i < gr.imagearray.size(); i++) {
								String url = gr.imagearray.get(i).getPic_url();
								// Logger.e(TAG, "131");
								File file = ImageLoader.getInstance().getDiskCache().get(url);
								// Logger.e(TAG, "132");
								if (file.exists()) {
									// Logger.e(TAG, "133");
									// if (file.lastModified() <
									// gr.getPic_time() *
									// 1000) {
									// ImageLoader.getInstance().loadImage(url,
									// imageOptions, new ImageLoadingListener()
									// {
									//
									// @Override
									// public void onLoadingStarted(String arg0,
									// View
									// arg1) {
									// // TODO Auto-generated method stub
									//
									// }
									//
									// @Override
									// public void onLoadingFailed(String arg0,
									// View
									// arg1, FailReason arg2) {
									// // TODO Auto-generated method stub
									//
									// }
									//
									// @Override
									// public void onLoadingComplete(String
									// arg0, View
									// arg1, Bitmap arg2) {
									// // TODO Auto-generated method stub
									//
									// }
									//
									// @Override
									// public void onLoadingCancelled(String
									// arg0, View
									// arg1) {
									// // TODO Auto-generated method stub
									//
									// }
									// });
									// }
								} else {
									// Logger.e(TAG, "164");
									ImageLoader.getInstance().loadImage(url, imageOptions, new ImageLoadingListener() {

										@Override
										public void onLoadingStarted(String arg0, View arg1) {
											// TODO Auto-generated method stub

										}

										@Override
										public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
											// TODO Auto-generated method stub

										}

										@Override
										public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
											// TODO Auto-generated method stub

										}

										@Override
										public void onLoadingCancelled(String arg0, View arg1) {
											// TODO Auto-generated method stub

										}
									});
								}
							}
						}

					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		};
		HttpTask httpTask = GetAds.getads(mActivity.getApplicationContext(), simpleResponseListener);
		ApiClinet.getInstance().doHttpTask(httpTask, simpleResponseListener);

	}

	public static GetAds.Result getAdsInfo(Context mContext) {
		GetAds.Result result = null;
		try {
			Gson gson = new Gson();
			String json = net.bblot.lottery.util.AppConfig.getJson(mContext, "ads");
			result = gson.fromJson(json, GetAds.Result.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static void saveAdsInfo(Context mContext, GetAds.Result result) {
		try {
			Gson gson = new Gson();
			net.bblot.lottery.util.AppConfig.saveJson(mContext, "ads", gson.toJson(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
